package cn.wolfcode.cloud.shop.mq.listener;

import cn.wolfcode.cloud.shop.consts.MQConstants;
import cn.wolfcode.cloud.shop.mq.msg.CreateOrderMsg;
import cn.wolfcode.cloud.shop.mq.msg.DelayOrderMsg;
import cn.wolfcode.cloud.shop.resp.Result;
import cn.wolfcode.cloud.shop.service.IOrderInfoService;
import cn.wolfcode.cloud.shop.util.JSONUtil;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Component
@RocketMQMessageListener(
    topic = MQConstants.SECKILL_ORDER_TOPIC,
    consumerGroup = MQConstants.CREATE_SECKILL_ORDER_CONSUMER_GROUP,
    selectorExpression = MQConstants.CREATE_SECKILL_ORDER_TAG
)
public class CreateSeckillOrderMQListener implements RocketMQListener<CreateOrderMsg> {

    private Logger logger = LoggerFactory.getLogger("CREATE_SECKILL_ORDER_MQ_LISTENER");

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(CreateOrderMsg createOrderMsg) {
        logger.info("收到创建订单消息:{}"+ JSONUtil.toJsonString(createOrderMsg));
        try {
            String orderNo = orderInfoService.doSeckill(createOrderMsg.getSeckillId(), createOrderMsg.getUserId());
            Map<String,Object> data = new HashMap<>();
            data.put("orderNo",orderNo);
            data.put("uuid",createOrderMsg.getUuid());
            rocketMQTemplate.syncSend(MQConstants.SECKILL_ORDER_SUCCESS_DEST, Result.success(data));
            //发送延迟消息,在30分钟检查订单是否支付
            DelayOrderMsg delayOrderMsg = new DelayOrderMsg(orderNo,createOrderMsg.getSeckillId(),createOrderMsg.getUserId());
            GenericMessage<DelayOrderMsg> msg = new GenericMessage<>(delayOrderMsg);
            rocketMQTemplate.syncSend(MQConstants.DELAY_ORDER_DEST,msg,3000,3);
        } catch (Exception e) {
            logger.error("订单创建失败:",e);
        }

    }
}
